﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace EBA.Data
{
    /// <summary>
    /// 可枚举集合工具集。
    /// </summary>
   public static  class EnumerableEx
    {
       /// <summary>
       /// 获取两个指定集合的差异集。
       /// </summary>
       /// <param name="originalValues">旧的数据集</param>
       /// <param name="currentValues">新的数据集</param>
       public static ChangeSet<TOriginalValue, TCurrentValue> GetChangeSet<TOriginalValue, TCurrentValue>(this IEnumerable<TOriginalValue> originalValues, IEnumerable<TCurrentValue> currentValues, Func<TOriginalValue, TCurrentValue, bool> predicate)
       {
           var changeSet = new ChangeSet<TOriginalValue, TCurrentValue>();

           changeSet.Added = currentValues.ToList();

           foreach (var o in originalValues)
           {
               //It should be deleted if it does not exists in currentValues
               if (changeSet.Added.Any(i => predicate(o, i)) == false)
               {
                   changeSet.Deleted.Add(o);
               }
               else//It may be updated if it exists in currentValues
               {
                   var modified = changeSet.Added.Where(i => predicate(o, i)).FirstOrDefault();
                   changeSet.Modified.Add(o, modified);
                   changeSet.Added.Remove(modified);//remove it from cached list.
               }
           }

           return changeSet;

       }

       public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
       {
           var list = new ObservableCollection<T>();

           foreach (var i in source)
           {
               list.Add(i);
           }

           return list;
       }
    }
}
